import 'package:BeeApp/MainPage/MainOrderModel.dart';
import 'package:BeeApp/MainPage/MainToolPage.dart';
import 'package:BeeApp/MainPage/http_request.dart';
import 'package:BeeApp/ShopPage/UserOrderNewsPage.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class UserOrderListPage01 extends StatefulWidget {
  UserOrderListPage01({Key key}) : super(key: key);

  @override
  _UserOrderListPage01State createState() => _UserOrderListPage01State();
}

class _UserOrderListPage01State extends State<UserOrderListPage01> {
  MainOrderListModel listModel;
  List<MainOrderCellModel> cellArr = [];
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);
  int page;
  bool requested = false;

  void _onRefresh() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use refreshFailed()
    page = 1;
    cellArr?.clear();
    getCellNews();
    requested = true;
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use loadFailed(),if no data return,use LoadNodata()
    // items.add((items.length + 1).toString());
    page = page + 1;
    getCellNews();
    if (mounted) setState(() {});
    _refreshController.loadComplete();
  }

  @override
  void initState() {
    super.initState();
    _onRefresh();
  }

  void getCellNews() {
    DioUtils.postHttp(
      context,
      "Usercommon/my_orders",
      parameters: {
        "token": getData("token"),
        "type": '1',
        "page": this.page.toString(),
      },
      onSuccess: (t) {
        print(t);
        if (mounted) {
          setState(() {
            listModel = MainOrderListModel.fromJson(t);
            if (listModel.code == 1) {
              List<MainOrderCellModel> arr = listModel.data;
              for (var i = 0; i < arr.length; i++) {
                print(arr[i]);
                cellArr.add(arr[i]);
              }
            }
          });
        }
      },
      onError: (error) {
        print(error);
      },
    );
  }

  Text textLabel01(String str) {
    return Text(
      str,
      style: TextStyle(
        color: Color(0xFF666666),
        fontSize: setFontSize(28),
      ),
    );
  }

  Widget textLabel02(String str) {
    return Container(
      width: (screenWidth - setWidth(150)) / 2,
      child: Text(
        str,
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(
          color: Color(0xFF333333),
          fontSize: setFontSize(28),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFFF5F5F5),
      body: SmartRefresher(
        enablePullDown: true,
        enablePullUp: true,
        header: WaterDropHeader(),
        footer: CustomFooter(
          builder: (BuildContext context, LoadStatus mode) {
            Widget body;
            if (mode == LoadStatus.idle) {
              body = Text("上拉加载");
            } else if (mode == LoadStatus.loading) {
              body = CupertinoActivityIndicator();
            } else if (mode == LoadStatus.failed) {
              body = Text("加载失败！点击重试！");
            } else if (mode == LoadStatus.canLoading) {
              body = Text("松手,加载更多!");
            } else {
              body = Text("没有更多数据了!");
            }
            return Container(
              height: 55.0,
              child: Center(child: body),
            );
          },
        ),
        controller: _refreshController,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: cellArr == null || cellArr.length == 0
            ? requested
                ? Center(child: Text('暂无订单'))
                : Container()
            : ListView.builder(
                itemCount: cellArr.length,
                itemBuilder: _listItemBuilder,
              ),
      ),
    );
  }

  Widget _listItemBuilder(BuildContext context, int index) {
    return Container(
      padding: EdgeInsets.only(top: setHeight(10)),
      child: InkWell(
        onTap: () {
          String orderID = cellArr[index].id.toString();
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => UserOrderNewsPage(orderID)),
          ).then((value) {
            _onRefresh();
          });
        },
        child: Container(
          padding: EdgeInsets.fromLTRB(
            setWidth(30),
            setHeight(20),
            setWidth(30),
            setHeight(10),
          ),
          color: Colors.white,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: <Widget>[
                  textLabel01("下单时间:"),
                  textLabel01(cellArr[index].createtimeText),
                ],
              ),
              SizedBox(height: setHeight(8)),
              Row(
                children: <Widget>[
                  textLabel02(
                      "${cellArr[index].sArea} · ${cellArr[index].sTitle}"),
                  SizedBox(width: setWidth(10)),
                  Image.asset(
                    "images/MainAddressToImage.png",
                    width: setWidth(50),
                  ),
                  SizedBox(width: setWidth(10)),
                  textLabel02(
                      "${cellArr[index].rArea} · ${cellArr[index].rTitle}")
                ],
              ),
              SizedBox(height: setHeight(8)),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Expanded(
                    child: Text(
                      "备注：${cellArr[index].goodsRemark}",
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        color: Color(0xFF666666),
                        fontSize: setFontSize(28),
                      ),
                    ),
                  ),
                  SizedBox(width: setWidth(10)),
                  Text("${cellArr[index].orderPrice}元",
                      style: TextStyle(
                        color: Color(0xFF222222),
                        fontSize: setFontSize(36),
                        fontWeight: FontWeight.bold,
                      ))
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}
